/**
 * Copyright 2005 The Apache Software Foundation
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.edi.runtime.component
{
    import com.edi.runtime.Event.*;
    
    import flash.external.ExternalInterface;
    import flash.geom.Point;
	
	/**
	 * 生成html编辑器 
	 * 
	 */	
	public class EDIHTMLEdit extends EDIHtmlPlan implements IEDIComponent
	{
		private var _htmlUrl: String;
        protected var iframeId:String;

        private var containerDict:Object = null;
        private var settingDict:Object = null;
        
        
		private var _field:String;
		private var _fieldtype:String;
		private var _fieldlength:int; 
		private var _notNull:Boolean;
		private var _table:String;
		private var _primaryKey:String="";
		private var _text:String="";
		private var _commitProperties:Boolean=false
        
		/**
        * Here we define javascript functions which will be inserted into the DOM
        * 
        */
        private static var FUNCTION_CREATEIFRAME:String = 
            "document.insertScript = function ()" +
        	"{ " +
                "if (document.createIFrame==null)" + 
                "{" + 
                    "createIFrame = function (frameID)" +
                	"{ " +
                		"try{"+
                        "var bodyID = document.getElementsByTagName(\"body\")[0];" +
                        "var newDiv = document.createElement('div');" +
                        "newDiv.id = frameID;" +
                        "newDiv.style.position ='absolute';" +
                        "newDiv.style.backgroundColor = 'transparent';" + 
                        "newDiv.style.border = '0px';" +
                        "newDiv.style.visibility = 'hidden';" +
                        "bodyID.appendChild(newDiv);" +
                        "}catch(err){}"+
                    "}" +
                "}" +
            "}";
        
        private static var FUNCTION_MOVEIFRAME:String = 
            "document.insertScript = function ()" +
        	"{ " +
	            "if (document.moveIFrame==null)" +
	            "{" +
	                "moveIFrame = function(frameID, iframeID, x,y,w,h) " + 
	                "{" +
	                	"try{"+
	                    "var frameRef=document.getElementById(frameID);" +
	                    "frameRef.style.left=x;" + 
	                    "frameRef.style.top=y;" +
	                    "var iFrameRef=document.getElementById(iframeID);" +
	                	"iFrameRef.width=w;" +
	                	"iFrameRef.height=h;" +
	                	"}catch(err){}"+
		            "}" +
                "}" +
            "}";

        private static var FUNCTION_HIDEIFRAME:String = 
            "document.insertScript = function ()" +
        	"{ " +
	            "if (document.hideIFrame==null)" +
	            "{" +
	                "hideIFrame = function (frameID)" +
                    "{" +
                    	"try{"+
                        "document.getElementById(frameID).style.visibility='hidden';" +
                        "}catch(err){}"+
                    "}" +
                "}" +
            "}";

        private static var FUNCTION_SHOWIFRAME:String = 
            "document.insertScript = function ()" +
        	"{ " + 
	            "if (document.showIFrame==null)" +
	            "{" +
	                "showIFrame = function (frameID)" +
                    "{" +
                    	"try{"+
                        "document.getElementById(frameID).style.visibility='visible';" +
                        "}catch(err){}"+
                    "}" +
                "}" +
            "}";

        private static var FUNCTION_LOADIFRAME:String = 
            "document.insertScript = function ()" +
        	"{ " +
	            "if (document.loadIFrame==null)" +
	            "{" +
	                "loadIFrame = function (frameID, iframeID, url)" +
                    "{" +
                    	"try{" + 
                        "document.getElementById(frameID).innerHTML = \"<iframe id='\"+iframeID+\"' src='\"+url+\"' frameborder='0'></iframe>\";" +
                        "}catch(err){}"+
                    "}" +
                "}" +
            "}";
        
        private static var FUNCTION_SETHTML:String = 
				"document.insertScript = function ()" +
	        	"{ " + 
	                "if (document.setTextToEditor==null)" + 
	                "{" + 
	                    "setTextToEditor = function(frameID,value)" +
	                	"{ " +
	                		"try{" + 
	                		"document.all.fck.value=value;"+
	                		"var oEditor = window.frames[frameID].FCKeditorAPI.GetInstance(\"fck\"); " +
	                        "oEditor.SetHTML(value);"+
	                        //"window.alert('set value: '+value);" + 
	                        "}catch(err){}"+
	                    "}" +
	                "}" +
	            "}";
		
		private static var FUNCTION_GETHTML:String = 
				"document.insertScript = function ()" +
	        	"{ " +
	                "if (document.getTextFromEditor==null)" + 
	                "{" + 
	                    "getTextFromEditor = function(frameID)" +
	                	"{ " +
	                		"try{"+
	                		"var oEditor = window.frames[frameID].FCKeditorAPI.GetInstance(\"fck\"); " +
	                        "return oEditor.GetXHTML(true); " +
	                         "}catch(err){}"+
	                    "}" +
	                "}" +
	            "}";
		
		private static var FUNCTION_DISABLED:String = 
				"document.insertScript = function ()" +
	        	"{ " +
	                "if (document.disabledFromEditor==null)" + 
	                "{" + 
	                    "disabledFromEditor = function(frameID)" +
	                	"{ " +
	                		"try{"+
	                		"var oEditor = window.frames[frameID].FCKeditorAPI.GetInstance(\"fck\"); " + 
	                		"if(oEditor!=null){" + 
		                		"var value=oEditor.GetXHTML(true);" + 
		                		"if(oEditor.EditorDocument!=null){" + 
			                        "oEditor.EditorDocument.designMode = \"Off\"; "+ 
			                        "oEditor.SetHTML(value);"+
		                        "}"+
	                        "}" +
	                        "}catch(err){}"+
	                    "}" + 
	                "}" + 
	            "}";
		
		/**
		 *  构造fckEdit控件
		 *  <EDIHTMLEdit x="0" y="0" width="100%" height="100%" id="txtMemo" htmlUrl = "/frame/FCKEditor.jsp">
		 *  </EDIHTMLEdit> 
		 */		
		public function EDIHTMLEdit()
		{
			super();
		}
		/**
		 * 实现IEDIComponent接口的属性，设置表名。 
		 * @param value 表名
		 * 
		 */
		public function set table(value:String):void
		{
			_table=value;
			EDIEventProxy.listenerDataRolling(value,this); 
		}
		
		public function get table():String
		{return _table;}
		
		/**
		 * 实现IEDIComponent接口的属性，设置是否是主键 
		 * @param value
		 * 
		 */	
		public function set primaryKey(value:String):void
		{_primaryKey=value;}
		public function get primaryKey():String
		{return _primaryKey;}
		
		/**
		 * 是否允许为空  
		 * @param value
		 * 
		 */	
		public function set notNull(value:Boolean):void
		{_notNull=value;}
		public function get notNull():Boolean
		{return _notNull;}
		
		/**
		 *  实现IEDIComponent接口的属性，设置字段名 
		 * @param value
		 * 
		 */	
		public function set field(value:String):void
		{_field=value;}
		public function get field():String
		{return _field;}
		
		/**
		 * 实现IEDIComponent接口的属性，设置字段类型 
		 * @param value
		 * 
		 */	
		public function set fieldType(value:String):void
		{
			_fieldtype=value;
		}
		public function get fieldType():String
		{return _fieldtype;}
		
		/**
		 * 实现IEDIComponent接口的属性，设置字段长度 
		 * @param value
		 * 
		 */	
		public function set fieldLength(value:int):void
		{
			_fieldlength=value;
		}
		public function get fieldLength():int
		{return _fieldlength;}
		
		/**
		 * 实现IEDIComponent接口的属性，捕获数据滚动 
		 * @param event
		 * 
		 */
		public function dataRollingHandler(event:EDIDataEvent):void
		{
			text=event.value[field];
		}
		/**
		 * 返回数据绑定时所需要的值  
		 * @return 
		 * 
		 */	
		public function get ediValue():String
		{
			return text;
		}
		
		/**
        * Generate DOM elements and build display path.
        * 
        */
        override protected function createChildren():void
        {
            
           
            // Generate unique id's for frame div name
            super.createChildren();
            frameId = id;
            iframeId = "iframe_"+frameId;
            
            // Add functions to DOM if they aren't already there
            ExternalInterface.call(FUNCTION_CREATEIFRAME);
            ExternalInterface.call(FUNCTION_LOADIFRAME);
            ExternalInterface.call(FUNCTION_DISABLED);  
            ExternalInterface.call(FUNCTION_SETHTML);
            ExternalInterface.call(FUNCTION_GETHTML);                        
            ExternalInterface.call(FUNCTION_MOVEIFRAME);
            ExternalInterface.call(FUNCTION_HIDEIFRAME);
            ExternalInterface.call(FUNCTION_SHOWIFRAME); 
            
            ExternalInterface.call("createIFrame", frameId);
//            if(_text!="")
//            {
//            	ExternalInterface.call("setTextToEditor",iframeId,text);
//            }
            registerSelf();
        }
        
        /**
        * Adjust frame position to match the exposed area in the application.
        * 
        */
        private function moveIFrame(): void
        {

            var localPt:Point = new Point(0, 0);
            var globalPt:Point = this.localToGlobal(localPt);

            ExternalInterface.call("moveIFrame", frameId, iframeId, globalPt.x, globalPt.y, this.width, this.height);
        }

        /**
        * Triggered by change to component properties.
        * 
        */
		override protected function commitProperties():void
		{
			super.commitProperties();
			
            if (htmlUrl && _commitProperties==false)
            {
	            ExternalInterface.call("loadIFrame", frameId, iframeId, htmlUrl);

				// Trigger re-layout of iframe contents.
				ExternalInterface.call(this.visible?"showIFrame":"hideIFrame", frameId);	            
	            invalidateDisplayList();
	            _commitProperties=true;
            }
		}        
		
        /**
        * Triggered when display contents change. Adjusts frame layout.
        * 
        * @param unscaledWidth
        * @param unscaledHeight
        * 
        */
		override protected function updateDisplayList(unscaledWidth:Number, unscaledHeight:Number):void
		{
			super.updateDisplayList(unscaledWidth, unscaledHeight);
			
            moveIFrame();
		}
		
        /**
        * 设置网页地址
        * 
        * @param url 要打开的网页地址
        * 
        */
        public function set htmlUrl(htmlUrl: String): void
        {
            if (htmlUrl)
            {
                _htmlUrl = htmlUrl;

				invalidateProperties();                
            }
        }

        public function get htmlUrl(): String
        {
            return _htmlUrl;
        }
        
     
        override public function set visible(visible: Boolean): void
        {
            super.visible=visible;
			
            if (visible)
            {
                ExternalInterface.call("showIFrame", frameId);
            } 
            else  
            {
            	disabled();
                ExternalInterface.call("hideIFrame", frameId);
            }  
        } 
        
        /**
         * 设置该fckedit的值
         * @param text
         * 
         */        
        public function set text(text:String):void
		{
			EDIApplication.outputDebug("value: "+text);
			ExternalInterface.call("setTextToEditor",iframeId,text);
			_text=text;
		}
		
		/**
		 * 获得 该fckedit的值
		 * @return 
		 * 
		 */		
		public function get text():String 
		{
			var value:String=ExternalInterface.call("getTextFromEditor",iframeId);
			//取出的值 为 空           //取值前visible=true执行过    //执行了visible=false 但未执行=true
			//return value==null?"":(value==_text?value:(value=="" && _text!=""?_text:value));
			return value==null?"":value;
		}
		
		/**
		 *  使fckedit处于非编辑状态
		 * 
		 */		
		public function disabled():void
		{
			ExternalInterface.call("disabledFromEditor",iframeId);
		}
	}
}